/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.remote.channel;

import com.googlecode.actorom.impl.remote.channel.protocol.Ack;
import com.googlecode.actorom.impl.remote.channel.protocol.Command;
import com.googlecode.actorom.impl.remote.channel.protocol.ServerCommand;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.jcip.annotations.ThreadSafe;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class RemoteChannel {

    private static final transient Logger LOG = LoggerFactory.getLogger(RemoteChannel.class);
    private final Lock stateLock = new ReentrantLock();
    private final String host;
    private final int port;
    private final ServerBootstrap server;
    private final ChannelGroup acceptedChannels;
    private Channel serverChannel;

    public RemoteChannel(String host, int port, ServerCallback callback) {
        this.host = host;
        this.port = port;
        server = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
        server.setOption("reuseAddress", true);
        server.getPipeline().addLast(ObjectEncoder.class.getName(), new ObjectEncoder());
        server.getPipeline().addLast(ObjectDecoder.class.getName(), new ObjectDecoder());
        server.getPipeline().addLast(ServerHandler.class.getName(), new ServerHandler(callback));
        acceptedChannels = new DefaultChannelGroup(this.toString());
    }

    public void bind() throws IOException {
        stateLock.lock();
        try {
            if (serverChannel == null) {
                serverChannel = server.bind(new InetSocketAddress(host, port));
                LOG.info("Bound message channel to: {}:{}", host, port);
            } else {
                throw new IllegalStateException("Request to bind an already active channel!");
            }
        } finally {
            stateLock.unlock();
        }
    }

    public void unbind() {
        stateLock.lock();
        try {
            if (serverChannel != null) {
                acceptedChannels.close().awaitUninterruptibly();
                serverChannel.close().awaitUninterruptibly();
                server.releaseExternalResources();
                serverChannel = null;
                LOG.info("Unbound message channel from: {}:{}", host, port);
            } else {
                throw new IllegalStateException("Request to unbind an inactive channel!");
            }
        } finally {
            stateLock.unlock();
        }
    }

    public boolean isBound() {
        stateLock.lock();
        try {
            return serverChannel != null;
        } finally {
            stateLock.unlock();
        }
    }

    @ChannelPipelineCoverage("all")
    private class ServerHandler extends SimpleChannelHandler {

        private ServerCallback callback;

        public ServerHandler(ServerCallback callback) {
            this.callback = callback;
        }

        @Override
        public void channelOpen(ChannelHandlerContext context, ChannelStateEvent event) throws Exception {
            acceptedChannels.add(event.getChannel());
        }

        @Override
        public void messageReceived(ChannelHandlerContext context, MessageEvent event) throws Exception {
            final Object payload = event.getMessage();
            final Channel channel = event.getChannel();
            if (payload instanceof ServerCommand) {
                ServerCommand command = (ServerCommand) payload;
                command.execute(callback, new ResponseCallback() {

                    public void write(Command command) {
                        channel.write(command);
                    }

                    public void write(Ack ack) {
                        channel.write(ack);
                    }
                });
            } else {
                throw new IllegalStateException("Unexpected command of type: " + payload.getClass());
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext context, ExceptionEvent event) throws Exception {
            LOG.debug(event.getCause().getMessage(), event.getCause());
        }
    }
}
